package com.wingsfrog.travel.service.impl;

import com.wingsfrog.travel.modules.dao.TaskDao;
import com.wingsfrog.travel.modules.dao.TeamTaskDao;
import com.wingsfrog.travel.modules.entity.Task;
import com.wingsfrog.travel.modules.entity.TeamTask;
import com.wingsfrog.travel.service.TeamTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;

/**
 * Created by rankin on 16/4/2.
 */
@Service
public class TeamTaskServiceImpl implements TeamTaskService {
    //接受任务
    //完成任务
    @Autowired
    private TeamTaskDao teamTaskDao;
    @Autowired
    private TaskDao taskDao;

    @Override
    public TeamTask getLastTeamTask(Integer teamId) {
        TeamTask lastTask = teamTaskDao.getTop1ByTeamIdOrderBySequenceDesc(teamId);
        return lastTask;
    }

    private Task getNextTask(Integer mainTaskId, Integer sequence) throws Exception {
        Task taskToAccept = taskDao.findByMainTaskIdAndSequence(mainTaskId, sequence);
        if (taskToAccept == null) throw new Exception("任务已经全部完成");
        return taskToAccept;
    }

    @Override
    public TeamTask acceptTaskByTeamIdAndMainTaskIdAndSequence(Integer teamId, Integer mainTaskId, Integer sequence) throws Exception {
        Task taskToAccept = getNextTask(mainTaskId, sequence);

        TeamTask teamTask = new TeamTask();
        Timestamp now = new Timestamp(System.currentTimeMillis());
        teamTask.setAcceptedAt(now);
        teamTask.setCheckpoint(taskToAccept.getCheckpoint());
        teamTask.setCreatedAt(now);
        teamTask.setEnabled(taskToAccept.getEnabled());
        teamTask.setFinished((byte) 0);
        teamTask.setSequence(taskToAccept.getSequence());
        teamTask.setTaskDescription(taskToAccept.getTaskDescription());
        teamTask.setTaskId(taskToAccept.getId());
        teamTask.setTaskScore(taskToAccept.getTaskScore());
        teamTask.setTaskName(taskToAccept.getTaskName());
        teamTask.setTaskType(taskToAccept.getTaskType());
        teamTask.setUpdatedAt(now);
        teamTask.setTeamId(teamId);
        teamTaskDao.save(teamTask);
        return teamTask;
    }
}
